﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using Dataglot;

namespace IrishSettings
{
    public class ResetSettings:GenericCommand
    {
        public ResetSettings(DataFactory factory)
            : base(factory)
        {
            const string sql = @"
delete from {$ns}_settings_values WHERE id 
in 
    (select id from {$ns}_settings_schema where application_id 
        in 
            (select id from {$ns}_settings_applications WHERE 
    application= @application 
    AND version= @version)
    )

";
            ComposeSql(sql);
            AddParameter("@application", DbType.String);
            AddParameter("@version", DbType.String);
        }

        public int Execute(
            string application,
            Version version
            )
        {
            if (string.IsNullOrEmpty(application))
                throw new ArgumentException("Missing application name", "application");
            if (version==null)
                throw new ArgumentException("Missing version", "version");

            command.Parameters["@application"].Value = application;
            command.Parameters["@version"].Value = version.ToString();
            return ExecuteNonQuery();
        }

        public int ResetAllVersions(
            string application
            )
        {
            if (string.IsNullOrEmpty(application))
                throw new ArgumentException("Missing application name", "application");

//            DELETE from {$ns}_settings_schema WHERE
//    id in (select id from {$ns}_settings_schema where application_id in (select id from {$ns}_settings_applications
//    where application =  @application 
//))

            const string sql = @"DELETE from {$ns}_settings_values WHERE
    schema_id in (select id from {$ns}_settings_schema where application_id in (select id from {$ns}_settings_applications
    where application =  @application 
))

";
            ComposeSql(sql);
            command.Parameters.Clear();
            AddParameter("@application", DbType.String);

            command.Parameters["@application"].Value = application;
            return ExecuteNonQuery();
        }
    }
}
